/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	Dotnetnuke PA module 
	Copyright (c) 2004, Oliver Hine (oliver.hine@gmail.com)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


************************************************************************************************/
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using DotNetNuke;
using Votations.NSurvey;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.WebControls.UI;
using Votations.NSurvey.Enums;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.WebControlsFactories;

namespace Votations.NSurvey.WebAdmin
{
	public class SurveyContentBuilder : PageBase
	{
		protected SurveyListControl SurveyList;
		protected System.Web.UI.WebControls.Label MessageLabel;
		protected System.Web.UI.WebControls.PlaceHolder QuestionListPlaceHolder;
		protected System.Web.UI.WebControls.Label Label1;
		protected System.Web.UI.WebControls.Literal SurveyBuilderTitle;
		protected HeaderControl Header;
		private QuestionData _questionsData = new QuestionData();

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			
			CreateLinks();
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				SetupSecurity();

				SurveyBuilderTitle.Text = GetPageResource("SurveyBuilderTitle");

				if (!Page.IsPostBack)
				{
					SurveyList.SurveyId = SurveyId;
					SurveyList.BindDropDown();
					Header.SurveyId = SurveyId;
				}

				// Build the survey's questions
				BuildQuestionList();
			}
			catch( Exception exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this,exc);
			}
		}

		private void SetupSecurity()
		{
			CheckRight(NSurveyRights.AccessFormBuilder, true);
		}

		/// <summary>
		/// Builds the Question list table with
		/// the edit options
		/// </summary>
		private void BuildQuestionList()
		{
			_questionsData = new Questions().GetQuestions(SurveyId);
			int currentPage = 1,
				previousDisplayOrder = 0,
				totalPages = new Surveys().GetPagesNumber(SurveyId);
			
			Table questionsContainer = new Table();
			questionsContainer.Width = Unit.Percentage(100);
			Table questionTable = new Table();
			questionTable.CellSpacing = 2;
			questionTable.CellPadding = 4;
			questionTable.CssClass = "questionBuilder";
			
			// always add first page 
			questionTable.Rows.Add(BuildPageBreakOptionsRow(currentPage, totalPages,previousDisplayOrder));
	
			foreach (QuestionData.QuestionsRow question in _questionsData.Questions.Rows)
			{
				while (question.PageNumber > currentPage)
				{
					currentPage++;

					questionsContainer.Rows.Add(BuildRow(questionTable));
					QuestionListPlaceHolder.Controls.Add(questionsContainer);

					// Creates a new page
					questionsContainer = new Table();
					questionsContainer.Width = Unit.Percentage(100);
					questionTable = new Table();
					questionTable.CellSpacing = 2;
					questionTable.CellPadding = 4;
					questionTable.CssClass = "questionBuilder";
					questionTable.Rows.Add(BuildPageBreakOptionsRow(currentPage, totalPages, previousDisplayOrder));
				}

				if (question.PageNumber == currentPage)
				{
					AddQuestionWebControl(questionTable, question);
					previousDisplayOrder = question.DisplayOrder;
				}
			}

			questionsContainer.Rows.Add(BuildRow(questionTable));
			QuestionListPlaceHolder.Controls.Add(questionsContainer);
		}

		/// <summary>
		/// Get a web control instance of the question row 
		/// and adds it with its options to the table 
		/// </summary>
		private void AddQuestionWebControl(Table questionTable, QuestionData.QuestionsRow question)
		{
			QuestionItem questionWebControl = QuestionItemFactory.Create(question, this.UniqueID, 0, null, true);

			// Set question's style
			// and bind the data
			Style questionStyle = new Style();
			questionStyle.CssClass = "surveyQuestion";
			Style answerStyle = new Style();
			answerStyle.CssClass = "surveyAnswer";	
			Style markStyle = new Style();

			if (questionWebControl is ActiveQuestion)
			{
				((ActiveQuestion)questionWebControl).EnableClientSideValidation = false;
				((ActiveQuestion)questionWebControl).EnableServerSideValidation = false;
			}
			if (questionWebControl is MatrixQuestion)
			{
				((MatrixQuestion)questionWebControl).MatrixHeaderStyle = answerStyle;
				((MatrixQuestion)questionWebControl).MatrixItemStyle = answerStyle;
				((MatrixQuestion)questionWebControl).MatrixAlternatingItemStyle = answerStyle;
			}

			questionWebControl.AnswerStyle = answerStyle;
			questionWebControl.QuestionStyle = questionStyle;

			questionWebControl.DataBind();
						
			// Add the question and its options to the table
			questionTable.Rows.Add(BuildQuestionOptionsRow(question));
			questionTable.Rows.Add(BuildRow(questionWebControl));
		}

		/// <summary>
		/// Builds a row with the options available to the question
		/// </summary>
		/// <returns>a tablerow instance with the options</returns>
		private TableRow BuildQuestionOptionsRow(QuestionData.QuestionsRow question)
		{
			// Creates a new edit options control
			QuestionOptionsControl questionOptions = 
				(QuestionOptionsControl)LoadControl("UserControls/QuestionOptionsControl.ascx");
			questionOptions.Question = question;
			questionOptions.QuestionCount = _questionsData.Questions.Rows.Count;
			return BuildRow(questionOptions);
		}

		/// <summary>
		/// Builds a row with the options available for page breaks
		/// </summary>
		/// <returns>a tablerow instance with the options</returns>
		private TableRow BuildPageBreakOptionsRow(int pageNumber, int totalPages, int previousDisplayOrder)
		{
			// Creates a new edit page break options control
			PageBreakOptionsControl pageBreakOptionsControl = 
				(PageBreakOptionsControl)LoadControl("UserControls/PageBreakOptionsControl.ascx");
			pageBreakOptionsControl.SurveyId = SurveyId;
			pageBreakOptionsControl.PageNumber = pageNumber;
			pageBreakOptionsControl.TotalPagesNumber = totalPages;
			pageBreakOptionsControl.PreviousQuestionDisplayOrder = previousDisplayOrder;
			
			return BuildRow(pageBreakOptionsControl);
		}

		
		private TableRow BuildRow(Control child)
		{
			TableRow row = new TableRow();
			TableCell cell  = new TableCell();
			cell.Controls.Add(child);
			row.Cells.Add(cell);
			return row;
		}
	}
}
